import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class main {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        //1.设置数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/lzq?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("111111");

        //2.建立连接
        Connection connection = dataSource.getConnection();

        //3.构造sql语句
        System.out.print(
            "1.增: insert into sign1(tableName) values(sign2(id),sign3(name));\n" +
            "2.删:delete from sign1(tableName) where sign2(condition);sign3为null\n" +
            "3.改:update sign1(tableName) set sign2(update) where sign3(condition); \n" +
            "4.查:select sign1(sign) from sign2(tableName) where sign3(condition);\n"
        );

        System.out.println("choice = ");
        int choice = scanner.nextInt();

        System.out.println("sign1 = ");
        String sign1 = scanner.next();

        System.out.println("sign2 = ");
        String sign2 = scanner.next();

        System.out.println("sign3 = ");
        String sign3 = scanner.next();

        Operation[] operation = {new Create(sign1,sign2,sign3),new Delete(sign1,sign2,sign3),
                new Update(sign1,sign2,sign3),new Retrieve(sign1,sign2,sign3)};
        String sql = operation[choice-1].operation();
        //4.执行sql,把解析后的sql语句发送给服务器
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        if(choice == 4) {
            ResultSet resultSet = preparedStatement.executeQuery();
            while(resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                System.out.println("id = "+id+", name = "+name);
            }
        }else {
            int n = preparedStatement.executeUpdate();
            System.out.println(n);
        }

        preparedStatement.close();;
        connection.close();
    }
}
